package com.dmy.chat.server.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;

/**
 * create by YCQ for 2020/1/13 9:25
 */
public abstract class ChannelManager<T> implements ChannelSender<T> , IChannelManager{
    private static  ChannelManager INSTANCE;
    protected static final ChannelGroup CHANNELS=new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    protected ChannelManager(){ }
    public static final ChannelManager getInstance(){
        if(INSTANCE == null) {
            synchronized (ChannelManager.class) {
                if (INSTANCE == null) {
                    Iterator<ChannelManager> iterator = ServiceLoader.load(ChannelManager.class).iterator();
                    if(iterator.hasNext()){
                        INSTANCE = iterator.next();
                    }
                }
            }
        }
        return INSTANCE;
    }

    /**
     * 添加客户端
     * @param channel
     */
    @Override
    public void addClient(Channel channel){
        CHANNELS.add(channel);
    }


    /**
     *  获取客户端
     * @param channelId
     * @return
     */
    @Override
    public Channel getClient(ChannelId channelId) {
        return CHANNELS.find(channelId);
    }
}
